package ag.data;

import ag.webpage.Position;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import img.AgImgUtil;
import util.HtmlUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @description:
 * @author: 张德长 dechang.zhang@ucarinc.com
 * @date: 13:05:19 2018/11/28
 * @version:2.0
 */
public class Retrieval {
    Map<Integer, List<String>> desksResult = new HashMap();
    public static String url = "http://www.buziman.com:8080/test/setAg?data=";

    /**
     * 获取原始数据
     **/
    public void getRawData(File srcFile) {
        BufferedImage screenSnapShot = getBufferedImage(srcFile);
        for (int deskId = 0; deskId < Position.positions.length; deskId++) {
            int[] position = Position.positions[deskId];
            BufferedImage elementSnapShot = AgImgUtil.getPositionBufferedImage(screenSnapShot, position);
            List<String> rawData = AgImgUtil.writeSingle(elementSnapShot);
            desksResult.put(deskId, rawData);
        }
        //System.out.println(JSON.toJSON(desksResult).toString());
    }

    /**
     * 获取图片
     **/
    public BufferedImage getBufferedImage(File srcFile) {
        try {
            BufferedImage bufferedImage = ImageIO.read(srcFile);
            return bufferedImage;
        } catch (IOException e) {
            System.out.println("读取屏幕截图出错");
            e.printStackTrace();
        }
        return null;
    }

    public List<String> exceptEqual(List<String> result) {
        List<String> resultExceptEqual = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            String data = result.get(i);
            if ("和".equals(data)) {
                continue;
            }
            resultExceptEqual.add(data);
        }
        return resultExceptEqual;
    }

    public void desksResultDeal() {
        Iterator<Integer> it = desksResult.keySet().iterator();
        Map map = new HashMap();
        StringBuffer htmlContent = new StringBuffer("[");
        while (it.hasNext()) {
            Integer deskId = it.next();
            List<String> result = desksResult.get(deskId);
            List<String> exceptEqual = exceptEqual(result);
            String[] strings = new String[exceptEqual.size()];
            exceptEqual.toArray(strings);
            htmlContent.append(JSONArray.toJSON(exceptEqual).toString() + ",");
            map.put(deskId, JSONArray.toJSON(exceptEqual).toString());

        }
        String mapString = JSON.toJSONString(map);
        String json = URLEncoder.encode(mapString);
        HtmlUtil.get(url + json);

    }

}
